<?php
namespace app\api\model\wine;

use app\common\model\BaseModel;
use app\api\service\wine\Dermember as DermemberService;

class Dermember extends BaseModel{
    protected $autoWriteTimestamp = true;
    public function user(){
        return $this->hasOne(\app\common\model\User::class,'user_id','user_id')
            ->with('avatar')
            ->bind(['mobile','nick_name','avatar_url']);
    }

    // 添加经销商
    public static function addDer($param){
        $pid = $param['pid'] ?? 0;
        $gain_type = $param['gain_type'] ?? 1;

        $data = [
            'store_id' => getStoreId(),
            'pid'=> $pid,
            'user_id'=> $param['user_id']
        ];

        try{
            // 判断pid是否有效推荐者
            if($pid != 0){
                $r = self::where(['user_id'=>$pid])->findOrEmpty();
                if($r->isEmpty()){
                    return false;
                }
            }
            // 判断pid是否自己
            if($pid == $param['user_id']){
                return false;
            }
            // 判断经销商不存在则执行创建
            $ur = self::where(['user_id'=>$param['user_id']])->findOrEmpty();
            if($ur->isEmpty()){
                // 创建推荐者记录
                return self::transaction(function () use($param,$gain_type,$data){
                    // 创建经销商用户
                    self::create($data);
                    DermemberService::distribution($param['user_id'],$gain_type);
                    return true;
                });
            }
        }catch (\Exception $exception){
            throwError($exception->getMessage(),500);
        }
        return false;
    }
    // 获取经销商信息
    public static function getDerInfo($user_id){
        return self::where(['user_id'=>$user_id,'store_id'=>getStoreId()])
            ->with('user')
            ->find();
    }

    // 获取我的推荐者1-3级别
    private static $level = 0;

    /**
     * 根据user_id获取我的推荐者1-3级别
     * @param int $user_id
     * @param array $data
     * @param int $level
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRecommend(int $user_id,array & $data,int $level = 3)
    {
        self::$level ++;
        $pid = (int)self::where(['user_id' => $user_id])->value('pid');
        $r = self::where(['user_id' => $pid])->find();
        if(empty($r)){
            return;
        }
        $data[self::$level] = $r->toArray();
        if(self::$level < $level){
            self::getRecommend($pid,$data);
        }
    }

    // 根据user_id获取pid
    public static function getPid(int $user_id):int
    {
        $pid = self::where(['user_id'=>$user_id])->value('pid');
        return empty($pid)? 0:(int)$pid;
    }

    /**
     * 增加或减少金币
     * @param int $user_id
     * @param float $step
     * @param string $type inc增加 dec减少
     * @return false|mixed
     */
    public static function setGold(int $user_id, float $step, string $type = 'inc')
    {
        return self::transaction(function () use ($user_id, $type, $step) {
            switch ($type) {
                case 'inc':
                    (new static)->setInc(['user_id' => $user_id], 'gold', $step);
                    break;
                case 'dec':
                    (new static)->setDec(['user_id' => $user_id], 'gold', $step);
                    break;
            }
            // 结算余额
            $r = self::where(['user_id' => $user_id, 'is_delete' => 0])
                ->field('gold,gold_cash')
                ->find();
            $gold_balance = (float)$r['gold'] - (float)$r['gold_cash'];
            return self::where(['user_id' => $user_id, 'is_delete' => 0])->save([
                'gold_balance' => $gold_balance, // 计算余额
            ]);
        });
    }

    /**
     * 提取金币
     * @param int $user_id
     * @param float $step
     * @return false|mixed
     */
    public static function setCashGold(int $user_id, float $step,int $cash_type=1)
    {
        return self::transaction(function () use($user_id,$step,$cash_type){
            // 添加金币支取记录
            DegainCash::buildRecord($user_id,$step,$cash_type);
            $r = self::where(['user_id'=>$user_id,'is_delete'=>0])
                ->field('gold,gold_cash')
                ->find();
            $gold_balance = (float) $r['gold'] - (float) $r['gold_cash'];
            // 增加提取余额
            (new static)->setInc(['user_id'=>$user_id,'is_delete'=>0],'gold_cash',$step);
            return self::where(['user_id'=>$user_id,'is_delete'=>0])->save([
                'gold_balance'=>$gold_balance, // 计算余额
            ]);
        });
    }

    /**
     * 增加或减少人数
     * @param int $user_id
     * @param int $step
     * @param string $type inc增加 dec减少
     * @return false|mixed
     */
    public static function setPcount(int $user_id,int $step,$type = 'inc'){
        switch ($type){
            case 'inc':
                return (new static)->setInc(['user_id'=>$user_id],'pcount',$step);
            case 'dec':
                return (new static)->setDec(['user_id'=>$user_id],'pcount',$step);
            default:
                return false;
        }
    }

    // 获取经销商下线人数排名
    public static function pCountList(){
        return self::with('user.avatar')
            ->order('pcount desc')
            ->paginate(15);
    }

    // 我的金币榜单
    public static function goldList(){
        return self::where(['is_delete'=>0,'store_id'=>getStoreId()])
            ->with('user')
            ->order('gold','desc')
            ->paginate(15);
    }

    // 金币余额
    public static function getGoldBalance(int $user_id){
        return self::where(['user_id'=>$user_id,'is_delete'=>0])->value('gold_balance');
    }
}
